<?php
namespace app\index\controller;

use app\common\entity\Config;
use app\common\entity\MywalletLog;
use app\common\entity\User;
use app\common\shop\OrderModel;
use app\common\shop\ShopGroupModel;
use app\common\shop\UserAgentLevelModel;
use app\common\shop\UserAreaLevelModel;
use app\common\shop\UserHouseLevelModel;
use app\common\shop\UserLevelModel;
use app\common\shop\UserTeamLevelModel;
use think\Db;
use think\Request;
use think\Controller;
// 定时任务
class Time extends Controller {
    /**
     * [团购-时间到期-完成拼团]
     * 一分钟执行一次
     * @param
     * @return
     */
    public function groupover( Request $request ){
        $list = ShopGroupModel::where('status',0)
            ->where('overtime','<=',time())
            ->select()->toArray();
        if(empty($list)) return '没有数据';
        $id = '';
        foreach ($list as $key => $value) {
            //$order = OrderModel::where('groupid',$value['id'])->select()->toArray();
            OrderModel::where('groupid',$value['id'])->update(['groupstatus'=>1]);
            ShopGroupModel::where('id',$value['id'])->update(['status'=>1,'finishtime'=>time()]);
            $id .= $value['id'].'-';
        }
        return '计算完成'.$id;
    }

    /**
     * [等级-每个月执行一次-每月一号（暂定每月一号）]
     * @param
     * @return
     */
    public function level( Request $request ){
//        $teamLevel = UserAgentLevelModel::field('id,name,direct,team,selfperformance,teamperformance,teamlevelid,teamnumber')
//            ->order('id asc')
//            ->find();// 第一个等级

        $user = User::column('id');// 全部会员id
        if(empty($user)) return '没有会员';
        $uid = '';
        foreach ($user as $key => $value) {

            $up = UserLevelModel::level($value);
           /* if($value == 215759){
                print_r($up);
            }*/
            $uid .= $value.'-';
        }
        return '会员：'.$uid;
    }

    /**
     * [团长奖励]
     * @param
     * @return
     */
    public function teamCommission(){
        // V1 V2没有级差 ->where('id',215744)
        $user = User::field('id,team_level')->where('team_level','>',0)->select()->toArray();

        if(!$user) return '没有会员是团长等级';
        // field('id,name,percentage')
        $teamlevel = UserTeamLevelModel::column('id,percentage');

        foreach ($user as $key => $value) {
            // 奖励比例
            $userLevelPer = $teamlevel[$value['team_level']];
            $this->teamUserData = [];// 会员重置
            $this->teamUser($value['id'],$value['team_level'],$value['team_level']);// 查找会员
            $teamUserData = $this->teamUserData;// 会员

            $allmoney = 0;

            foreach ($teamUserData as $k => $v) {
                // 得到奖励比例
                if($k== $value['team_level']){
                    $fee = $userLevelPer;
                }else{
                    $fee = $userLevelPer - $teamlevel[$k];
                }

                if($fee <=0) continue;// 小于0则调入下一个循环
                $sumPerformance =array_sum( array_column($v,'performance'));
                if($sumPerformance > 0){
                    $money = $sumPerformance * $fee/100;
                    // 得到的奖励
                    $allmoney +=$money;
                }
            }

            if($allmoney >0){
                MywalletLog::addLog($value['id'], $allmoney, 4, '团长奖', 17, 1);
            }
        }

        User::where('performance','>',0)->setField('performance',0);// 奖业绩清0
        return '完成';
    }
    private $teamUserData = [];
    /**
     * [会员下级等级]
     * @param
     * @return
     */
    public function teamUser($uid,$team_level = 0,$newlevel = 0,$teamUser=[]){
        // 下级会员-团长等级要大于下级
        $team = User::field('id,pid,team_level,performance,nick_name')->where('team_level','<',$team_level)->where('pid','in',$uid)->select()->toArray();

        if(empty($team)) return $teamUser;// 已经没有会员
        $puid = '';
        foreach ($team as $key => $value) {
            if($value['team_level'] == 0){
                // 没有等级
                $teamUser[0][]= $value;
                $this->teamUserData[$newlevel][]= $value;
                $puid = $value['id'].',';
            }else{
                // 是否就是下一级等级
                $teamUser[$value['team_level']][$value['id']] = $value;
                $this->teamUserData[$value['team_level']][]= $value;
                return $this->teamUser($value['id'],$team_level,$value['team_level']);
            }
        }
        if(empty($puid)) return $teamUser;
//        $puid = array_column($team,'id');
//        $teamUser = array_merge($teamUser,$team);
        return $this->teamUser(trim($puid,','),$team_level,$newlevel,$teamUser);
    }

    /**
     * [下级业绩]
     * @param
     * @return
     */
    public function teamU($uid,$team_level,$teamUser=[]){
        $team = User::field('id,team_level,performance,nick_name')->where('team_level','<',$team_level)->where('pid','in',$uid)->select()->toArray();
        if(empty($team)) return $teamUser;// 已经没有会员
        $puid = array_column($team,'id');
        $teamUser = array_merge($teamUser,$team);

        return $this->teamU($puid,$team_level,$teamUser);
    }


    public function team(){

        print_r(json_decode(json_encode(UserLevelModel::team()),true));
    }


    /**
     * [分红]
     * @param
     * @return
     */
    public function profit(){
        $all_money_order = Config::getValue('all_money_order');
        if(empty($all_money_order)){
            // field('id,total')->
            $all_money_order = OrderModel::where('status','in','2,3')->where('isshare',0)->sum('total');
        }
        if($all_money_order<=0) return '没有业绩';
        /*//团长等级
        $teamLevel = UserTeamLevelModel::where('peers','>',0)->select()->toArray();

        if($teamLevel){

            foreach ($teamLevel as $key => $value) {
                $userTeam = User::where('team_level',$value['id'])->column('id');
               
                if(empty($userTeam)) continue;
                $count = count($userTeam);
                $money = ($all_money_order*$value['peers']/100)/$count;
                if($money>0){
                    foreach ($userTeam as $k => $v) {
                        MywalletLog::addLog($v, $money, 4, '团长分红', 18, 1);
                    }
                }
            }
        }*/
        // 代理等级（VIP）
        $useragentlevel = UserAgentLevelModel::where('fenhong','>',0)->select();
        if($useragentlevel){

            foreach ($useragentlevel as $key => $value) {
                $userTeam = User::where('agent_level',$value['id'])->column('id');
                if(empty($userTeam)) continue;
                $count = count($userTeam);
                $money = ($all_money_order*$value['fenhong']/100)/$count;
                if($money>0){
                    foreach ($userTeam as $k => $v) {
                        MywalletLog::addLog($v, $money, 4, $value['name'].'奖励', 18, 1);
                    }
                }
            }
        }
        // 房主等级
        $userhouselevel = UserHouseLevelModel::where('peers','>',0)->select();
        if($userhouselevel){
            foreach ($userhouselevel as $key => $value) {
                $userTeam = User::where('house_level',$value['id'])->column('id');
                if(empty($userTeam)) continue;
                $count = count($userTeam);
                $money = ($all_money_order*$value['peers']/100)/$count;
                if($money>0){
                    foreach ($userTeam as $k => $v) {
                        MywalletLog::addLog($v, $money, 4, $value['name'].'奖励', 18, 1);
                    }
                }
            }
        }
        // 区域代理等级
        $user_area_level = UserAreaLevelModel::where('peers','>',0)->select();
        if($user_area_level){
            foreach ($user_area_level as $key => $value) {
                $userTeam = User::where('area_level',$value['id'])->column('id');
                if(empty($userTeam)) continue;
                $count = count($userTeam);
                $money = ($all_money_order*$value['peers']/100)/$count;
                if($money>0){
                    /*if($value['id'] == 1){
                        $title = '区代理奖励';
                    }elseif($value['id'] ==2){
                        $title = '市代理奖励';
                    }elseif($value['id']==3){
                        $title = '省代理奖励';
                    }*/
                    // $value['name'].'区域代理分红'
                    foreach ($userTeam as $k => $v) {
                        // MywalletLog::addLog($v, $money, 4, $title, 18, 1);
                        MywalletLog::addLog($v, $money, 4, $value['name'].'奖励', 18, 1);
                    }
                }
            }
        }
        OrderModel::where('status','in','2,3')->where('isshare',0)->setField('isshare',1);
        return '完成';
    }

}